{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "a61e04e9-b09b-4cc6-9ed4-d612105751c8",
   "metadata": {},
   "source": [
    "# Creating a Barplot With seaborn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb4fc26b-f8b3-4018-9630-6b8e0b9ee75d",
   "metadata": {},
   "outputs": [],
   "source": [
    "! python -m pip install seaborn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c3a45935-7f1d-4917-aea9-e7a2fa07e5b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "tips = sns.load_dataset(\"tips\")\n",
    "\n",
    "(\n",
    "    sns.barplot(\n",
    "        data=tips, x=\"day\", y=\"tip\", estimator=\"mean\", errorbar=None\n",
    "    ).set(title=\"Daily Tips ($)\")\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5f3ba970-6707-4017-9f34-19109546f89d",
   "metadata": {},
   "outputs": [],
   "source": [
    "tips[\"day\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a1b349bd-9192-4150-bad9-9ef3d3ab8617",
   "metadata": {},
   "source": [
    "# Creating a Barplot With Matplotlib"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "265d2288-16f3-40b9-ba31-f55cc8ed3788",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "\n",
    "tips = pd.read_csv(\"tips.csv\")\n",
    "\n",
    "average_daily_tip = tips.groupby([\"day\"])[\"tip\"].mean()\n",
    "\n",
    "days = [\"Thur\", \"Fri\", \"Sat\", \"Sun\"]\n",
    "daily_averages = [\n",
    "    average_daily_tip[\"Thur\"],\n",
    "    average_daily_tip[\"Fri\"],\n",
    "    average_daily_tip[\"Sat\"],\n",
    "    average_daily_tip[\"Sun\"],\n",
    "]\n",
    "\n",
    "fig, ax = plt.subplots()\n",
    "plt.bar(x=days, height=daily_averages)\n",
    "ax.set_xlabel(\"day\")\n",
    "ax.set_ylabel(\"tip\")\n",
    "ax.set_title(\"Daily Tips ($)\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99c6f382-090f-4c80-8be8-ed2b6d174414",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "tips = sns.load_dataset(\"tips\")\n",
    "\n",
    "(\n",
    "    sns.barplot(data=tips, x=\"day\", y=\"tip\", estimator=\"mean\", errorbar=None)\n",
    "    .set_title(\"Daily Tips ($)\")\n",
    "    .figure.savefig(\"output.png\")\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0c79404b-2c79-404a-8624-fd935bc53a7d",
   "metadata": {},
   "source": [
    "# Using Axes Level Functions\r\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "43a85f66-f553-4fb3-a649-c9677c5ef04d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b74f20e-34bf-4e14-ad9e-a90da3e6f644",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "(\n",
    "    sns.scatterplot(data=crossings, x=\"min_temp\", y=\"max_temp\").set(\n",
    "        title=\"Minimum vs Maximum Temperature\",\n",
    "        xlabel=\"Minimum Temperature\",\n",
    "        ylabel=\"Maximum Temperature\",\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e5ef924d-dd91-4bf0-a4b0-d00bbc7f9bde",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "(\n",
    "    sns.scatterplot(\n",
    "        data=crossings,\n",
    "        x=\"min_temp\",\n",
    "        y=\"max_temp\",\n",
    "        hue=\"month\",\n",
    "        size=\"month\",\n",
    "        style=\"month\",\n",
    "    ).set(\n",
    "        title=\"Minimum vs Maximum Temperature\",\n",
    "        xlabel=\"Minimum Temperature\",\n",
    "        ylabel=\"Maximum Temperature\",\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.legend(title=\"Month\")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f4ee43f-0802-443d-b09f-0ce1c61f07d1",
   "metadata": {},
   "source": [
    "# Using Figure Level Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff9ae42d-5e9d-44c3-898a-5f4ff6120230",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "(\n",
    "    sns.relplot(\n",
    "        data=crossings,\n",
    "        x=\"min_temp\",\n",
    "        y=\"max_temp\",\n",
    "        kind=\"scatter\",\n",
    "        hue=\"month\",\n",
    "        col=\"month\",\n",
    "    )\n",
    "    .set(\n",
    "        title=\"Minimum vs Maximum Temperature\",\n",
    "        xlabel=\"Minimum Temperature\",\n",
    "        ylabel=\"Maximum Temperature\",\n",
    "    )\n",
    "    .legend.set_title(\"Month\")\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "088ce486-f897-476d-8c57-8ee80d6daf48",
   "metadata": {},
   "source": [
    "# Introducing seaborn’s Contemporary Objects Interface"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a62215b8-247f-4eb2-b26d-e19ec75e3b44",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "(so.Plot(data=crossings, x=\"min_temp\", y=\"max_temp\").show())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c5c3bd9-3b64-4570-8512-5b862f5c34c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "(\n",
    "    so.Plot(data=crossings, x=\"min_temp\", y=\"max_temp\")\n",
    "    .add(so.Dot())\n",
    "    .label(\n",
    "        title=\"Minimum vs Maximum Temperature\",\n",
    "        x=\"Minimum Temperature\",\n",
    "        y=\"Maximum Temperature\",\n",
    "    )\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f988ea1a-cac0-4aa5-a05a-f731a24cb668",
   "metadata": {},
   "outputs": [],
   "source": [
    "(\n",
    "    so.Plot(data=crossings, x=\"min_temp\", y=\"max_temp\", color=\"month\")\n",
    "    .add(so.Dot(), marker=\"month\")\n",
    "    .label(\n",
    "        title=\"Minimum vs Maximum Temperature\",\n",
    "        x=\"Minimum Temperature\",\n",
    "        y=\"Maximum Temperature\",\n",
    "        color=str.capitalize,\n",
    "    )\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2addc2d9-55f2-4f24-86cf-a05d36bfd35c",
   "metadata": {},
   "outputs": [],
   "source": [
    "(\n",
    "    so.Plot(data=crossings, x=\"min_temp\", y=\"max_temp\", color=\"month\")\n",
    "    .add(so.Dot(), marker=\"month\")\n",
    "    .facet(col=\"month\")\n",
    "    .layout(size=(15, 5))\n",
    "    .label(\n",
    "        title=\"Minimum vs Maximum Temperature\",\n",
    "        x=\"Minimum Temperature\",\n",
    "        y=\"Maximum Temperature\",\n",
    "        color=str.capitalize,\n",
    "    )\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1e49cd9-a9f1-450d-8b0d-32638ed5acc4",
   "metadata": {},
   "source": [
    "# Creating Categorical Plots Using Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bc8f9db9-31e5-4631-bf57-41947cb99443",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "crossings.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "80d9ff5e-a208-481e-8aa0-afea553f0a09",
   "metadata": {},
   "outputs": [],
   "source": [
    "bridge_crossings = crossings.melt(\n",
    "    id_vars=[\"day\", \"date\"],\n",
    "    value_vars=[\"Brooklyn\", \"Manhattan\", \"Williamsburg\", \"Queensboro\"],\n",
    "    var_name=\"Bridges\",\n",
    "    value_name=\"Crossings\",\n",
    ").rename(columns={\"day\": \"Day\", \"date\": \"Date\"})\n",
    "\n",
    "bridge_crossings.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "11e95b75-ca04-4736-90e2-f57dc3619855",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "sns.barplot(\n",
    "    data=bridge_crossings,\n",
    "    x=\"Day\",\n",
    "    y=\"Crossings\",\n",
    "    hue=\"Bridges\",\n",
    "    errorbar=None,\n",
    "    estimator=\"sum\",\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68774aa2-b933-4a15-9756-4e1a67f98675",
   "metadata": {},
   "outputs": [],
   "source": [
    "wednesday_crossings = crossings.loc[crossings.day.isin([\"Wednesday\"])].rename(\n",
    "    columns={\"month\": \"Month\"}\n",
    ")\n",
    "\n",
    "(\n",
    "    sns.boxplot(\n",
    "        data=wednesday_crossings, x=\"day\", y=\"Williamsburg\", hue=\"Month\"\n",
    "    ).set(xlabel=None)\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bcdc42db-256b-400d-800f-d0c67983ee6a",
   "metadata": {},
   "source": [
    "## Exercise Solutions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a3d17195-add4-434c-ae10-53d8709e3668",
   "metadata": {},
   "source": [
    "**Task 1**: See if you can create multiple barplots for the weekend data only, with each day on a separate plot but in the same row. Each subplot should show the highest number of crossings for each bridge."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "72688b49-7b2a-49e4-bb5f-7d6097ef9104",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "bridge_crossings = crossings.melt(\n",
    "    id_vars=[\"day\", \"date\"],\n",
    "    value_vars=[\"Brooklyn\", \"Manhattan\", \"Williamsburg\", \"Queensboro\"],\n",
    "    var_name=\"Bridges\",\n",
    "    value_name=\"Crossings\",\n",
    ").rename(columns={\"day\": \"Day\", \"date\": \"Date\"})\n",
    "\n",
    "weekend = bridge_crossings.loc[\n",
    "    bridge_crossings.Day.isin([\"Saturday\", \"Sunday\"])\n",
    "]\n",
    "\n",
    "(\n",
    "    sns.catplot(\n",
    "        data=weekend,\n",
    "        x=\"Day\",\n",
    "        y=\"Crossings\",\n",
    "        hue=\"Bridges\",\n",
    "        col=\"Day\",\n",
    "        errorbar=None,\n",
    "        estimator=\"max\",\n",
    "        kind=\"bar\",\n",
    "    ).set(xlabel=None)\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8dfdea4-029c-476f-b1cc-c8df177a8559",
   "metadata": {},
   "source": [
    "**Task 2**: See if you can draw three boxplots in a row containing separate monthly crossings for the Brooklyn Bridge for Wednesdays only."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8464250c-6ef1-49cd-9ad3-19a779f8ce07",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "wednesday = crossings.loc[crossings.day.isin(values=[\"Wednesday\"])].rename(\n",
    "    columns={\"month\": \"Month\"}\n",
    ")\n",
    "\n",
    "(\n",
    "    sns.catplot(\n",
    "        data=wednesday, x=\"day\", y=\"Brooklyn\", col=\"Month\", kind=\"box\"\n",
    "    ).set(xlabel=None)\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7eb0364b-a126-4f67-b1c9-bc68bb29fd46",
   "metadata": {},
   "source": [
    "# Creating Distribution Plots Using Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cc895593-c0fd-4876-b9e2-73ac95807f0a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "cereals_data = pd.read_csv(\"cereals_data.csv\").rename(\n",
    "    columns={\"rating\": \"Rating\"}\n",
    ")\n",
    "\n",
    "cereals_data.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "91a2a115-5b47-4d24-8fc9-30ca7862efc7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "\n",
    "(\n",
    "    sns.histplot(data=cereals_data, x=\"Rating\", bins=10).set(\n",
    "        title=\"Cereal Ratings Distribution\"\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2ac59f03-0841-4dc8-9b68-7df46a61e49b",
   "metadata": {},
   "outputs": [],
   "source": [
    "(\n",
    "    sns.kdeplot(data=cereals_data, x=\"Rating\").set(\n",
    "        title=\"Cereal Ratings KDE Curve\"\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "612ea8e0-a1a4-484a-994a-e09b35389c4e",
   "metadata": {},
   "outputs": [],
   "source": [
    "sns.kdeplot(data=cereals_data, x=\"Rating\")\n",
    "\n",
    "(\n",
    "    sns.rugplot(data=cereals_data, x=\"Rating\", height=0.2, color=\"black\").set(\n",
    "        title=\"Cereal Rating Distribution\"\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c4c89f02-1659-48da-bbf8-b22c5bbad21d",
   "metadata": {},
   "source": [
    "## Exercise Solutions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22ca41f6-344a-4e62-b6b0-a8fb835dffae",
   "metadata": {},
   "source": [
    "**Task 1:** Produce a single histogram showing cereal ratings distribution such that there is a separate bar for each manufacturer. Keep to the same 10 bins."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0306d0f9-22bf-441b-b13e-82d77b1a58cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "cereals_data = pd.read_csv(\"cereals_data.csv\").rename(\n",
    "    columns={\"rating\": \"Rating\"}\n",
    ")\n",
    "\n",
    "sns.histplot(\n",
    "    data=cereals_data,\n",
    "    x=\"Rating\",\n",
    "    bins=10,\n",
    "    hue=\"manufacturer\",\n",
    "    multiple=\"dodge\",\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c46c4570-f99f-4397-80d8-1cf7edc7212b",
   "metadata": {},
   "source": [
    "**Task 2:** See if you can superimpose a KDE plot onto your original ratings histogram using only one functions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "455105e0-8f0b-4db9-bc56-4039a07e0c39",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "cereals_data = pd.read_csv(\"cereals_data.csv\").rename(\n",
    "    columns={\"rating\": \"Rating\"}\n",
    ")\n",
    "\n",
    "sns.histplot(data=cereals_data, x=\"Rating\", kde=True, bins=10)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b8016214-04d9-4263-9334-68a7f2ed653b",
   "metadata": {},
   "source": [
    "**Task 3**: Update your answer to task 1 such that each manufacturer's rating distribution appears on a separate plot and each has its own KDE curve."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1634f124-655c-499c-b990-8a703301c294",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "cereals_data = pd.read_csv(\"cereals_data.csv\").rename(\n",
    "    columns={\"rating\": \"Rating\", \"manufacturer\": \"Manufacturer\"}\n",
    ")\n",
    "\n",
    "sns.displot(\n",
    "    data=cereals_data,\n",
    "    x=\"Rating\",\n",
    "    bins=10,\n",
    "    hue=\"Manufacturer\",\n",
    "    kde=True,\n",
    "    col=\"Manufacturer\",\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5335b396-6884-40b6-9b9f-25beb626f0b6",
   "metadata": {},
   "source": [
    "# Creating Relational Plots Using Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b93b3955-7959-46e1-9a96-581c7a96ae9d",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "sns.set_theme(style=\"darkgrid\")\n",
    "\n",
    "(\n",
    "    sns.lineplot(data=crossings, x=\"date\", y=\"Brooklyn\").set(\n",
    "        title=\"Brooklyn Bridge Daily Crossings\", xlabel=None\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.xticks(\n",
    "    ticks=[\"01/04/2017\", \"01/05/2017\", \"01/06/2017\", \"30/06/2017\"], rotation=45\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1b98fd09-c86f-4017-b6b2-c2d76806d52c",
   "metadata": {},
   "source": [
    "## Exercise Solutions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bd55196b-3695-4320-a462-872bce310608",
   "metadata": {},
   "source": [
    "**Task 1**  Using an appropriate dataframe, produce a single line plot showing the crossings for all bridges from April to June."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5b4a2768-73aa-4367-a647-f9cb3400440a",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "bridge_crossings = crossings.melt(\n",
    "    id_vars=[\"day\", \"date\"],\n",
    "    value_vars=[\"Brooklyn\", \"Manhattan\", \"Williamsburg\", \"Queensboro\"],\n",
    "    var_name=\"Bridges\",\n",
    "    value_name=\"Crossings\",\n",
    ").rename(columns={\"day\": \"Day\", \"date\": \"Date\"})\n",
    "\n",
    "(\n",
    "    sns.lineplot(\n",
    "        data=bridge_crossings,\n",
    "        x=\"Date\",\n",
    "        y=\"Crossings\",\n",
    "        hue=\"Bridges\",\n",
    "        style=\"Bridges\",\n",
    "    ).set_title(\"Daily Bridge Crossings\")\n",
    ")\n",
    "\n",
    "plt.xticks(\n",
    "    ticks=[\"01/04/2017\", \"01/05/2017\", \"01/06/2017\", \"30/06/2017\"], rotation=45\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf6dae9d-014b-4bae-8411-ef8254381e85",
   "metadata": {},
   "source": [
    "**Task 2** Clarify your solution to exercise 1 by creating a separate subplot for each bridge."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "6ce5e4e7-6a3d-4842-94e1-5459ab819dce",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "bridge_crossings = crossings.melt(\n",
    "    id_vars=[\"day\", \"date\"],\n",
    "    value_vars=[\"Brooklyn\", \"Manhattan\", \"Williamsburg\", \"Queensboro\"],\n",
    "    var_name=\"Bridges\",\n",
    "    value_name=\"Crossings\",\n",
    ").rename(columns={\"day\": \"Day\", \"date\": \"Date\"})\n",
    "\n",
    "sns.relplot(\n",
    "    data=bridge_crossings,\n",
    "    kind=\"line\",\n",
    "    x=\"Date\",\n",
    "    y=\"Crossings\",\n",
    "    hue=\"Bridges\",\n",
    "    col=\"Bridges\",\n",
    ")\n",
    "\n",
    "plt.xticks(\n",
    "    ticks=[\"01/04/2017\", \"01/05/2017\", \"01/06/2017\", \"30/06/2017\"], rotation=45\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e1b5c68f-e6b5-4fcd-85f4-3c199612e682",
   "metadata": {},
   "source": [
    "# Creating Regression Plots Using Functions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f9f95bcd-f3de-4228-b34b-961a6141d789",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "(\n",
    "    sns.regplot(data=crossings, x=\"min_temp\", y=\"max_temp\", ci=95).set(\n",
    "        title=\"Regression Analysis of Temperatures\",\n",
    "        xlabel=\"Minimum Temperature\",\n",
    "        ylabel=\"Maximum Temperature\",\n",
    "    )\n",
    ")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0007a6e6-4a78-4581-bf49-1dc1e2f74dac",
   "metadata": {},
   "outputs": [],
   "source": [
    "! python -m pip install scikit-learn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2b522852-582e-4995-a385-83f2b4d09a91",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "x = crossings.loc[:, [\"min_temp\"]]\n",
    "y = crossings.loc[:, \"max_temp\"]\n",
    "\n",
    "model = LinearRegression()\n",
    "model.fit(x, y)\n",
    "\n",
    "r_squared = f\"R-Squared: {model.score(x, y):.2f}\"\n",
    "best_fit = f\"y = {model.coef_[0]:.4f}\" + f\"x{model.intercept_:+.4f}\"\n",
    "\n",
    "ax = sns.regplot(\n",
    "    data=crossings,\n",
    "    x=\"min_temp\",\n",
    "    y=\"max_temp\",\n",
    "    line_kws={\"label\": best_fit + \"\\n\" + r_squared},\n",
    ")\n",
    "\n",
    "ax.set_xlabel(\"Minimum Temperature\")\n",
    "ax.set_title(\"Regression Analysis of Temperatures\")\n",
    "ax.set_ylabel(\"Maximum Temperature\")\n",
    "ax.legend()\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4334615-c7b1-47a4-b062-731e5c69e975",
   "metadata": {},
   "source": [
    "## Exercise Solutions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f229579-3f82-4752-8189-fd37b53d5bc1",
   "metadata": {},
   "source": [
    "**Task 1**: Redo the previous regression plot, but this time create a single plot showing a separate regression line, with equation, for each of the three months."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f490fa7d-6c2e-4218-b672-c935d6f23613",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "\n",
    "def calculate_regression(month, data):\n",
    "    x = data.loc[:, [\"min_temp\"]]\n",
    "    y = data.loc[:, \"max_temp\"]\n",
    "    model = LinearRegression()\n",
    "    model.fit(x, y)\n",
    "    r_squared = f\"R-Squared: {model.score(x, y):.2f}\"\n",
    "    best_fit = (\n",
    "        f\"{month}\\ny = {model.coef_[0]:.4f}\" + f\"x{model.intercept_:+.4f}\"\n",
    "    )\n",
    "    return r_squared, best_fit\n",
    "\n",
    "\n",
    "def drawplot(month, crossings):\n",
    "    monthly_crossings = crossings[crossings.month == month]\n",
    "    r_squared, best_fit = calculate_regression(month, monthly_crossings)\n",
    "\n",
    "    ax = sns.regplot(\n",
    "        data=monthly_crossings,\n",
    "        x=\"min_temp\",\n",
    "        y=\"max_temp\",\n",
    "        ci=None,\n",
    "        line_kws={\"label\": best_fit + \"\\n\" + r_squared},\n",
    "    )\n",
    "    ax.set_title(\"Regression Analysis of Temperatures\")\n",
    "    ax.legend()\n",
    "\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "months = [\"April\", \"May\", \"June\"]\n",
    "for month in months:\n",
    "    drawplot(month, crossings)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74f12cfd-3286-4131-89b5-304d3475e5e7",
   "metadata": {},
   "source": [
    "**Task 2**: Use an appropriate figure level function to create a separate regression plot for each month. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b933cb6b-ff0c-474b-8449-c729b55e5e09",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "sns.lmplot(data=crossings, x=\"min_temp\", y=\"max_temp\", col=\"month\")\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b930dbc7-cf3a-499a-a5ac-6c4506d5053e",
   "metadata": {},
   "source": [
    "**Task 3**: See if you can add the correct equation onto each of the three plots you created in task 2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "97d31415-689b-43c4-a253-025133a060ac",
   "metadata": {},
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "import seaborn as sns\n",
    "from sklearn.linear_model import LinearRegression\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "\n",
    "def regression_equation(data, **kws):\n",
    "    x = data.loc[:, [\"min_temp\"]]\n",
    "    y = data.loc[:, \"max_temp\"]\n",
    "    model = LinearRegression()\n",
    "    model.fit(x, y)\n",
    "    r_squared = f\"R-Squared: {model.score(x, y):.2f}\"\n",
    "    best_fit = f\"y = {model.coef_[0]:.4f}x\" + f\"{model.intercept_:+.4f}\"\n",
    "    ax = plt.gca()  # Get current Axes.\n",
    "    ax.text(\n",
    "        0.1,\n",
    "        0.6,\n",
    "        f\"{best_fit}{chr(10)}\" + f\"{r_squared}\",\n",
    "        transform=ax.transAxes,\n",
    "    )\n",
    "\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "sns.lmplot(\n",
    "    data=crossings, x=\"min_temp\", y=\"max_temp\", col=\"month\"\n",
    ").map_dataframe(regression_equation)\n",
    "\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f92c9d9-14f8-48a0-8835-146c4769bd72",
   "metadata": {},
   "source": [
    "# Using the Main Data Visualization Objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b7e2957-99d2-4224-9c0f-265b15e4fa0e",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "first_week = crossings.loc[crossings.month == \"April\"].head(7)\n",
    "\n",
    "(\n",
    "    so.Plot(data=first_week, x=\"day\", y=\"min_temp\")\n",
    "    .add(so.Line(color=\"black\", linewidth=3, marker=\"o\"))\n",
    "    .add(so.Bar(color=\"green\", fill=False, edgewidth=3))\n",
    "    .add(so.Area(color=\"yellow\"))\n",
    "    .label(x=\"Day\", y=\"Temperature\", title=\"Minimum Temperature\")\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2724c225-e2f9-4097-937a-8734fdccd34d",
   "metadata": {},
   "source": [
    "# Enhancing Your Plots With “Move” and “Stat” Objects"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cb0f3fe0-af96-4dba-bc75-fa2da4b20058",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "(\n",
    "    so.Plot(data=crossings, x=\"month\", y=\"max_temp\", color=\"day\")\n",
    "    .add(so.Bar(), so.Agg(func=\"median\"), so.Dodge(gap=0.1))\n",
    "    .label(x=None, y=\"Temperature\", title=\"Median Temperature\", color=\"Day\")\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b376e70-f7e7-4019-9aa6-16e34d7f738d",
   "metadata": {},
   "source": [
    "# Separating a Plot Into Subplots"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64d6d651-4559-447d-b096-da6e131b99a9",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "(\n",
    "    so.Plot(data=crossings, x=\"month\", y=\"max_temp\", color=\"day\")\n",
    "    .facet(col=\"month\")\n",
    "    .add(so.Bar(), so.Agg(func=\"median\"), so.Dodge(gap=0.1))\n",
    "    .label(x=None, y=\"Temperature\", title=\"Median Temperature\", color=\"Day\")\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6f3bb00b-6ad2-485e-ba03-350d0a038652",
   "metadata": {},
   "source": [
    "## Exercise Solutions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5869d9c1-0585-48c4-b52d-5e336f431e22",
   "metadata": {},
   "source": [
    "**Task 1:** Using the objects API, redraw the min_temperature vs max_temperature scatterplot you created at the start of the article using objects. Also, make sure each marker has a different color depending on the days it represents.  Finally, each marker should be represented by a star.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "abf2e82d-d84f-4261-b4c3-5ac1f9278fa4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "(\n",
    "    so.Plot(data=crossings, x=\"min_temp\", y=\"max_temp\", color=\"day\")\n",
    "    .add(so.Dot(marker=\"*\"))\n",
    "    .label(\n",
    "        x=\"Minimum Temperature\",\n",
    "        y=\"Maximum Temperature\",\n",
    "        title=\"Scatterplot of Temperatures\",\n",
    "    )\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e56bab6b-1d0d-463d-8537-d7efe6174016",
   "metadata": {},
   "source": [
    "**Task 2**: Using the objects API, create a barplot showing the maximum and minimum number of bridge crossings for each of the four bridges."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ebdd9fef-d523-4960-9d2c-367828225121",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "bridge_crossings = crossings.melt(\n",
    "    id_vars=[\"day\", \"date\"],\n",
    "    value_vars=[\"Brooklyn\", \"Manhattan\", \"Williamsburg\", \"Queensboro\"],\n",
    "    var_name=\"Bridges\",\n",
    "    value_name=\"Crossings\",\n",
    ")\n",
    "\n",
    "(\n",
    "    so.Plot(data=bridge_crossings, x=\"Bridges\", y=\"Crossings\", color=\"Bridges\")\n",
    "    .add(so.Bar(), so.Agg(\"max\"))\n",
    "    .add(so.Bar(), so.Agg(\"min\"))\n",
    "    .label(x=\"Bridge\", y=\"Crossings\", title=\"Bridge Crossings\")\n",
    "    .show()\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "25d3cbce-7a53-4f03-9efb-26609c39ab6e",
   "metadata": {},
   "source": [
    "**Task 3**: Using the objects API, create a barplot analyzing the counts of breakfast cereal calories. The calories should be placed into 10 equal-sized bins."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0eec3fcd-992c-4bf5-b5b1-3efdeda33a84",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import seaborn.objects as so\n",
    "\n",
    "crossings = pd.read_csv(\"cycle_crossings_apr_jun.csv\")\n",
    "\n",
    "cereals_data = pd.read_csv(\"cereals_data.csv\")\n",
    "\n",
    "(\n",
    "    so.Plot(data=cereals_data, x=\"calories\")\n",
    "    .add(so.Bar(), so.Hist(bins=10))\n",
    "    .label(x=\"Calories\", y=\"Count\", title=\"Calorie Counts\")\n",
    "    .show()\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
